using Microsoft.Extensions.Logging;
using TaskScheduler.Infrastructure.Configuration;

namespace TaskScheduler.Infrastructure.Services;

/// <summary>
/// 飞书消息服务
/// </summary>
public interface IFeishuService
{
    /// <summary>
    /// 发送文本消息到飞书
    /// </summary>
    /// <param name="title">消息标题</param>
    /// <param name="content">消息内容</param>
    /// <returns>是否发送成功</returns>
    Task<bool> SendMessageAsync(string title, string content);
}

/// <summary>
/// 飞书消息服务实现
/// </summary>
public class FeishuService : IFeishuService
{
    private readonly ILogger<FeishuService> _logger;
    private readonly IHttpClientFactory _httpClientFactory;

    public FeishuService(ILogger<FeishuService> logger, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 发送文本消息到飞书
    /// </summary>
    public async Task<bool> SendMessageAsync(string title, string content)
    {
        try
        {
            using var httpClient = _httpClientFactory.CreateClient();
            
            var payload = new
            {
                msg_type = "post",
                content = new
                {
                    post = new
                    {
                        zh_cn = new
                        {
                            title = title,
                            content = new object[][]
                            {
                                new object[]
                                {
                                    new { tag = "text", text = content }
                                }
                            }
                        }
                    }
                }
            };

            var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
            var httpContent = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
            
            var response = await httpClient.PostAsync(ApiConfig.FeishuWebhookUrl, httpContent);
            
            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("飞书消息发送成功: {Title}", title);
                return true;
            }
            else
            {
                _logger.LogWarning("飞书消息发送失败，状态码: {StatusCode}, 标题: {Title}", response.StatusCode, title);
                return false;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送飞书消息时发生错误，标题: {Title}", title);
            return false;
        }
    }
} 